package com.it.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.it.reggie.common.Result;
import com.it.reggie.entity.User;
import com.it.reggie.service.IUserService;
import com.it.reggie.utils.SMSUtils;
import com.it.reggie.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author:cyh
 * @data:2022/12/18 0:59
 */
@Api(tags = "用户管理")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public Result getCode(HttpServletRequest request, @RequestBody User user){
        //输入手机号 -> 点击获取验证码 -> 发送ajax请求后台
        //1、后台获取手机号【13399998888】
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //2、随机生成六位数字验证码【123456】  RandomUtil
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //3、调用SMSUtils,给该手机号发送相应的验证码短信
            //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
            //4、将该验证码存入到session中，使用手机号作为key，值就是验证码
            //-> 此时用户的手机应该收到了验证码短信：
            //将验证码存到session中
            //request.getSession().setAttribute(phone, code);

            //优化:将验证码存储到redis中,并设置过期时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.success("验证码发送成功");
        }

        return Result.filed("验证码发送失败");

    }

    @PostMapping("/login")
    public Result login(@RequestBody User user,HttpServletRequest request){
        //获取登录时输入的手机号和验证码
        String userCode = user.getCode();
        String phone = user.getPhone();
        //从session中取出生成的验证码
        //Object sysCode =request.getSession().getAttribute(phone);

        //从redis中获取缓存的验证码
        Object sysCode = redisTemplate.opsForValue().get(phone);

        //比较验证码
        if (sysCode!=null&&sysCode.equals(userCode)){
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User userLogin = userService.getOne(wrapper);
            //如果用户为空,则注册账号
            if (userLogin==null){
                userLogin = new User();
                userLogin.setPhone(phone);
                userLogin.setStatus(1);
                userService.save(userLogin);
                userLogin = userService.getOne(wrapper);
            }
            //将用户id存到session
            request.getSession().setAttribute("user", userLogin.getId());
            //登录成功删除redis中验证码
            redisTemplate.delete(phone);
            return Result.success("登录成功");
        }
        return Result.filed("登录失败");
    }

    @PostMapping("/loginout")
    public Result loginout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Result.success("已退出登录");
    }

}
